<template>
  <div class="personal-profile">
    <!-- 页面标题 -->
    <el-row>
      <el-col :span="24">
        <el-col :span="24">
          <van-nav-bar
            title="个人资料"
            left-text="返回"
            left-arrow
            @click-left="onClickLeft"
          />
        </el-col>
        <el-card class="box-card">
          <el-form :model="user" label-width="80px">
            <!-- 头像 -->
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="http://113.44.137.179:6001/user/feedback/fileUpload"
                name="file"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!-- 昵称 -->
            <el-form-item label="昵称">
              {{ user.name }}
              <el-button @click=updateName()> ></el-button>
            </el-form-item>
            <!-- 编号 -->
            <el-form-item label="编号">
              {{ user.bh }}
            </el-form-item>
            <!-- 生日 -->
            <span @click="dianji()">
            <el-form-item label="生日">
            {{ user.birth }}
            </el-form-item>
              </span>
          </el-form>
        </el-card>
        <van-popup v-model="show" position="bottom" :style="{ height: '70%' }">
          <!-- 关闭按钮 -->
          <div class="popup-close" @click="guanbi()">
            <el-button type="text" icon="el-icon-close" style="width: 20px"></el-button>
            <span class="popup-close-text">关闭</span>
          </div>
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="选择年月日"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="handleDateConfirm"
          />
        </van-popup>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import Vue from 'vue';
import {DatetimePicker, Toast} from 'vant';

Vue.use(DatetimePicker);
export default {
  data() {
    return {
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(2021, 0, 17),
      show: false,
      dialogFormVisible: false,
      user: {
        id: "",
        name: "",
        birth: "",
      },
      uid: "",
      from: {
        image: "",
      },
      imageUrl: "",
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      Toast.loading({ message: '上传图片中...', forbidClick: true });
      this.imageUrl = res;
      axios.post(`/user/user/updateAvatar`, {
        id: this.uid,
        image: this.imageUrl
      }).then(res => {
        if (res.data.code == 1) {
          this.$message.success('头像上传成功');
        } else {
          this.$message.error('头像上传失败');
        }
      })
    },
    beforeAvatarUpload(file) {
      Toast.loading({ message: '检测图片中...', forbidClick: true });
      return null;
    },
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      } else if (type === 'month') {
        return `${val}月`;
      }
      return val;
    },
    handleDateConfirm(date) {
      Toast.loading({ message: '修改生日中...', forbidClick: true });
      // 手动构建日期字符串格式
      let year = date.getFullYear();
      let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份需要加1并补0
      let day = String(date.getDate()).padStart(2, '0');
      let formattedDate = `${year}-${month}-${day}`;
      this.user.birth = formattedDate;
      console.log('选择的日期:', this.user.birth);
      axios.post("/user/user/updateBirthById", {
        id: this.uid,
        birth: formattedDate
      }).then(res => {
        if (res.data.code == 200) {
          console.log("生日更新成功");
          this.show = false
        } else {
          console.log("生日更新失败:", res.data.message);
        }
      }).catch(error => {
        console.error("更新生日出错:", error);
      });
    },
    guanbi() {
      this.show = false;
    },
    dianji() {
      // 将用户生日字符串转换为Date类型
      if (this.user.birth) {
        const birthDate = new Date(this.user.birth);
        this.currentDate = birthDate;
      }
      this.show = true;
    },
    findById() {
      axios.post("/user/user/findById?id=" + this.uid).then(res => {
        this.user = res.data.data;
        this.imageUrl = this.user.image;
        // 假设后端返回的birth是时间戳
        if (this.user.birth) {
          const birthTimestamp = this.user.birth;
          const birthDate = new Date(birthTimestamp);
          this.user.birth = birthDate.toISOString().split('T')[0];
        }
      })
    },
    updateName() {
      //跳转
      this.$router.push({path: '/edit'})
    },
    onClickLeft() {
      Toast('返回');
      //返回上一个页面
      this.$router.push('/myShow');
    },
  },
  mounted() {
    var user = localStorage.getItem('user');
    if (user) {
      this.from = JSON.parse(user);
      this.uid = this.from.id;
      console.log("uid=", this.uid)
    }
    this.findById();
  }
};
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader {
  text-align: left;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px solid #d9d9d9;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
